import React, {useState , CSSProperties, FC, ReactComponentElement , createContext} from "react";
import classNames from 'classnames'
import { tabItemProps } from "./tabItem";


type mode = 'card' | 'content';

//tabs组件的参数
export interface tabsProps {
    defaultIndex: number, 
    className?: string,
    style?:CSSProperties,
    mode?:mode,
    onSelect?:Function,
};  

//tabs组件的context
interface tabContextProps {
    onSelect?: (selectedIndex:number)=>void,
    index:number,
    mode:mode,
}



// const tabContext = createContext(0);


const Tabs: FC<tabsProps> = (props)=>{
    let {
        children,
        defaultIndex,
        className,
        style,
        mode,
        onSelect
    } = props;

    const [index, setIndex] = useState(defaultIndex);

    //class名
    const classnames = classNames('tabs' , className );

    //渲染子节点函数
    const renderChildren = ()=>{
        return React.Children.map(children , (item , index)=>{
            const childElement = item as React.FunctionComponentElement<tabItemProps>;
            const { displayName } = childElement.type;
            if(displayName === 'TabItem'){
                return React.cloneElement(childElement , {index: index}) ;
            }else{
               console.error('error: children is not tabItem'); 
            }
        });
    }

    const handleClick = (selectedIndex:number)=>{
        //切换
        setIndex(selectedIndex);
        
        //执行onSelect
        if(onSelect===undefined){
            console.log('onSelect is undefined');
        }else{
            onSelect();
        }
    };


    const tabStore:tabContextProps = {
        index: defaultIndex ? defaultIndex : 0,
        onSelect:handleClick,
        mode:mode as mode,
    }

    return <div className={classnames} style={style}>
        <TabConext.Provider value={tabStore}>
            {renderChildren()}
        </TabConext.Provider>
    </div>
}

Tabs.defaultProps = {
    defaultIndex:0,
}

Tabs.displayName = 'Tabs';

//创建index 、 onSelect
export const TabConext = createContext<tabContextProps>({
    index:0, 
    onSelect:()=>{},
    mode:'card' 
});

export default Tabs;